package com.ren.service.sms.rest;

import cn.hutool.core.util.RandomUtil;
import com.ren.common.exception.BusinessException;
import com.ren.common.result.R;
import com.ren.common.result.ResponseEnum;
import com.ren.service.sms.client.CoreUserInfoFeignClient;
import com.ren.service.sms.config.SmsProperties;
import com.ren.service.sms.model.vo.SendSmsReqVO;
import com.ren.service.sms.service.ISmsService;
import com.ren.common.constants.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author RenGaoshuai
 * @date 2023/8/7 18:26
 * @description
 */
@RequestMapping("/admin/sms")
@RestController
@Slf4j
public class SmsController {

    @Autowired
    private ISmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CoreUserInfoFeignClient coreUserInfoFeignClient;


    /**
     * 发送短信验证码
     * @param reqVO
     * @return
     */
    @PostMapping("/send")
    public R sendSms(@RequestBody SendSmsReqVO reqVO){

        //调用service-core服务校验手机号
        boolean mobileIsRegister = coreUserInfoFeignClient.checkMobile(reqVO.getMobile());
        if (!mobileIsRegister){
            throw new BusinessException(ResponseEnum.MOBILE_NOT_EXIST);
        }

        String code = RandomUtil.randomNumbers(4);
        //组装短信模板参数
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);

        //发送短信
        smsService.send(reqVO.getMobile(), SmsProperties.TEMPLATE_CODE, param);

        //将验证码存入redis，登陆的时候根据手机号取出对应的code验证即可
        redisTemplate.opsForValue().set(RedisKeyConstant.SMS_CODE_KEY + reqVO.getMobile(), code, 5, TimeUnit.MINUTES);

        return R.ok().message("发送成功");
    }
}
